//
//  AppDelegate.m
//  lingAo
//
//  Created by saxon on 16/9/20.
//  Copyright © 2016年 saxon. All rights reserved.
//

#import "AppDelegate.h"
#import "LALoginViewController.h"
#import "LAWebViewController.h"
#import "UMessage.h"
#import <RT_CommonToolkit/FrameHeader.h>

@interface AppDelegate ()

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookieAcceptPolicy:NSHTTPCookieAcceptPolicyAlways];
    
    NSLog(@"%@", NSHomeDirectory());
    
    
    [RTToolObject saveImageToLocation:@"hello@3x.png" url:URL(@"http://cdn.chinaz.com/tools/images/public/logos/logo-index.png") returnBlock:^(BOOL flag) {
        
    }];
    
    NSLog(@"%@", [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]);
    
    NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    NSString *userAgentstr = [NSString stringWithFormat:@"Mozilla/5.0 (iPhone; CPU iPhone OS 5_1 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Mobile/9B176 lingao/%@", version];
    [[NSUserDefaults standardUserDefaults] registerDefaults:@{@"UserAgent":userAgentstr}];
    
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor whiteColor];
    
    NSString *cookie = [[NSUserDefaults standardUserDefaults] objectForKey:@"cookie"];
    if (cookie) {
        self.window.rootViewController = [[UINavigationController alloc] initWithRootViewController:[[LAWebViewController alloc] init]];
    } else {
        self.window.rootViewController = [[LALoginViewController alloc] init];
    }
    
    if (launchOptions) {
        ///获取到推送相关的信息
        NSDictionary *userInfo = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
        
        [self dealPushData:userInfo];
    }
    
    [self.window makeKeyAndVisible];
    
    
    //友盟配置
    [UMessage startWithAppkey:@"57e3386367e58e3c49001c67" launchOptions:launchOptions];
    [self registerNotification];
    return YES;
}
// 注册推送
- (void)registerNotification{
    UIApplication *application = [UIApplication sharedApplication];
    application.applicationIconBadgeNumber = 0;
    
    if([application respondsToSelector:@selector(registerUserNotificationSettings:)])
    {
        UIUserNotificationType notificationTypes = UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert;
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:notificationTypes categories:nil];
        [application registerUserNotificationSettings:settings];
    }
    
    //iOS8 注册APNS
    if ([application respondsToSelector:@selector(registerForRemoteNotifications)]) {
        [application registerForRemoteNotifications];
    }else{
        UIRemoteNotificationType notificationTypes = UIRemoteNotificationTypeBadge |
        UIRemoteNotificationTypeSound |
        UIRemoteNotificationTypeAlert;
        [application registerForRemoteNotificationTypes:notificationTypes];
    }
    
    
    //register remoteNotification types (iOS 8.0以下)
    [UMessage registerForRemoteNotificationTypes:UIRemoteNotificationTypeBadge
     |UIRemoteNotificationTypeSound
     |UIRemoteNotificationTypeAlert];
}
// 将得到的deviceToken传给SDK
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    [UMessage registerDeviceToken:deviceToken];
    NSString *str = [[deviceToken description] stringByReplacingOccurrencesOfString:@" " withString:@""];
    str = [str stringByReplacingOccurrencesOfString:@"<" withString:@""];
    str = [str stringByReplacingOccurrencesOfString:@">" withString:@""];
    NSLog(@"deviceToken:%@", str);
    [[NSUserDefaults standardUserDefaults] setObject:str forKey:@"deviceToken"];
}

// 注册deviceToken失败
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error{
    NSLog(@"deviceToken -- %@",error);
}
- (void) application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    RTAlertView *alert = [[RTAlertView alloc] initWithTitle:nil message:[userInfo objectForKey:@"message"] cancelButtonTitle:@"取消" otherButtonTitles:@"前往" ReturnBlock:^(int index) {
        if (index == 1){
            [self dealPushData:userInfo];
        }
    }];
    [alert show];
    
    NSLog(@"%@", userInfo);
}
- (void)dealPushData:(NSDictionary *)userInfo
{
    if ([[userInfo objectForKey:@"type"] isEqualToString:@"pushNewsPageView"]) {
        NSLog(@"%@", self.window.rootViewController);
        if ([self.window.rootViewController isKindOfClass:[UINavigationController class]]) {
            id data = [userInfo objectForKey:@"data"];
            if ([data isKindOfClass:[NSDictionary class]]) {
                LAWebViewController *webVc = [[LAWebViewController alloc] initWithUrl:[data objectForKey:@"url"]];
                
                UINavigationController *nav = (UINavigationController *)self.window.rootViewController;
                [nav FitPushViewController:webVc animated:YES];
            }
        }
    }
}
- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end
